package main

import "math"

func isAlienSorted(words []string, order string) bool {
	orderMap := make(map[byte]int)
	for i, c := range []byte(order) {
		orderMap[c] = i
	}
	for i := 1; i < len(words); i++ {
		if compareStr(words[i], words[i-1], orderMap) < 0 {
			return false
		}
	}
	return true
}

//比较字符a和b
func compare(a, b byte, orderMap map[byte]int) int {
	return orderMap[a] - orderMap[b]
}

//比较字符串s1和s2
func compareStr(s1, s2 string, orderMap map[byte]int) int {
	l1, l2 := len(s1), len(s2)
	ml := int(math.Min(float64(l1), float64(l2)))
	for i := 0; i < ml; i++ {
		cmp := compare(s1[i], s2[i], orderMap)
		if cmp < 0 || cmp > 0 {
			return cmp
		}
	}
	return l1 - l2
}
